<template>
  <BasicModal
    width="1000px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :footer="null"
    :maskClosable="false"
  >
    <Button type="primary" @click="createComponentHandle">
      <template #icon><PlusOutlined /></template>
      新建
    </Button>
    <Table
      style="margin-top: 8px"
      :columns="componentColumns"
      :data-source="componentListData"
      :pagination="false"
      bordered
    >
      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.dataIndex === 'serialNumber'">
          <div>
            <span> {{ index + 1 }}</span>
          </div>
        </template>
        <template
          v-else-if="['componentTitle', 'componentCode', 'sort'].includes(column.dataIndex)"
        >
          <div>
            <a-input
              v-if="editableData[record.id]"
              v-model:value="editableData[record.id][column.dataIndex]"
              style="margin: -5px 0"
            />
            <template v-else> {{ text }} </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <Popconfirm title="确认保存?" @confirm="saveComponentHandle(record.id)">
                <a>保存</a>
              </Popconfirm>
              <a style="margin-left: 8px" @click="cancelComponentHandle(record.id)">取消</a>
            </span>
            <span v-else>
              <a @click="editComponentHandle(record.id)">编辑</a>
              <Popconfirm title="确认删除?" @confirm="removeComponentHandle(record.id)">
                <a style="margin-left: 8px">删除</a>
              </Popconfirm>
            </span>
          </div>
        </template>
      </template>
    </Table>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, reactive, ref, unref, UnwrapRef } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { Popconfirm, Table } from 'ant-design-vue';
  import {
    createComponent,
    queryComponentListByMenuId,
    modifyComponent,
    removeComponentById,
  } from '/@/api/system/system';
  import { ComponentReq, ComponentResp } from '/@/api/system/modal/componentModel';
  import { cloneDeep } from 'lodash-es';
  import { Button } from '/@/components/Button';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuComponentModal',
    components: {
      Button,
      PlusOutlined,
      Table,
      Popconfirm,
      BasicModal,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();

      const isUpdate = ref(true);
      const id = ref('');
      const loading = ref(false);

      const componentColumns = [
        {
          title: '序号',
          dataIndex: 'serialNumber',
          width: '10%',
        },
        {
          title: '组件名称',
          dataIndex: 'componentTitle',
          width: '25%',
        },
        {
          title: '组件编码',
          dataIndex: 'componentCode',
          width: '25%',
        },
        {
          title: '排序',
          dataIndex: 'sort',
          width: '15%',
        },
        {
          title: '操作',
          dataIndex: 'operation',
        },
      ];

      const componentListData = ref<ComponentResp[]>([]);

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        id.value = data?.record?.id;

        await getListData();
      });

      const getTitle = computed(() => '菜单控件');

      const editableData: UnwrapRef<Record<string, ComponentResp>> = reactive({});

      const getListData = async () => {
        const componentReq: ComponentReq = {
          menuId: unref(id),
        };
        componentListData.value = await queryComponentListByMenuId(componentReq);
      };
      const createComponentHandle = () => {
        const id = 'TmpKey';
        const componentResp: ComponentResp = {
          id: id,
        };
        componentListData.value.push(componentResp);
        editComponentHandle(id);
      };

      const editComponentHandle = (key: string) => {
        editableData[key] = cloneDeep(componentListData.value.filter((item) => key === item.id)[0]);
      };

      const saveComponentHandle = async (key: string) => {
        try {
          Object.assign(
            componentListData.value.filter((item) => key === item.id)[0],
            editableData[key],
          );

          const componentReq: ComponentReq = editableData[key];
          componentReq.menuId = unref(id);
          if (key === 'TmpKey') {
            componentReq.id = undefined;
            await createComponent(componentReq);
          } else {
            await modifyComponent(componentReq);
          }

          delete editableData[key];

          await getListData();
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          createMessage.error(msg);
        }
      };

      const cancelComponentHandle = (key: string) => {
        delete editableData[key];
      };

      const removeComponentHandle = async (key: string) => {
        try {
          const componentReq: ComponentReq = {
            id: key,
          };
          await removeComponentById(componentReq);
        } catch (error: any) {
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          createMessage.error(msg);
        }
        await getListData();
      };

      async function handleSubmit() {
        try {
          closeModal();
          emit('success', {
            isUpdate: unref(isUpdate),
            values: {},
          });
        } catch (error: any) {
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return {
        componentColumns,
        roleId: id,
        registerModal,
        getTitle,
        loading,
        componentListData,
        editableData,
        createComponentHandle,
        editComponentHandle,
        saveComponentHandle,
        cancelComponentHandle,
        removeComponentHandle,
        handleSubmit,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::-webkit-scrollbar {
    width: 3px;
    height: 6px;
  }

  ::-webkit-scrollbar-track-piece {
    background-color: rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:vertical {
    height: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }

  ::-webkit-scrollbar-thumb:horizontal {
    width: 3px;
    background-color: rgba(125, 125, 125, 0.7);
    -webkit-border-radius: 6px;
  }
</style>
